﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Tasks;
using Newtonsoft.Json;

namespace Metal_Archives
{
    public partial class Band : PhoneApplicationPage
    {
        CommonMethods cm = new CommonMethods();
        string name;
        string link;
        string color;

        public Band()
        {
            InitializeComponent();
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            //Don't do anything if you're returning to the page
            if (e.NavigationMode != System.Windows.Navigation.NavigationMode.Back)
            {
                name = this.NavigationContext.QueryString["name"];
                link = this.NavigationContext.QueryString["link"];
                this.sunroof.Title = name.ToLower();

                //Need to hide the color of the selected item, but need black or white depending on OS theme choice
                color = cm.themeFontColor();

                //Is the user connected to the internet?
                if (cm.isOnline())
                {
                    //Get data from site
                    WebClient wc = new WebClient();
                    wc.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wc_DownloadStringCompleted);
                    wc.DownloadStringAsync(new Uri(link));
                }
            }
            else
            {
                this.lsbDiscog.SelectedIndex = -1;
                this.lsbLinks.SelectedIndex = -1;
                this.lsbMembers.SelectedIndex = -1;
                this.lsbSimilarArtists.SelectedIndex = -1;
            }
        }

        void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            if (cm.isOnlineE(e))
            {
                HtmlAgilityPack.HtmlDocument bandHTML = new HtmlAgilityPack.HtmlDocument();
                bandHTML.LoadHtml(e.Result);

                //Load each pivot page's info
                Band_About(bandHTML);
                Band_Discog();
                Band_LogoPhoto(bandHTML);
                Band_Members(bandHTML);

                //Is the user connected to the internet?
                if (cm.isOnline())
                {
                    //Similar Artists
                    WebClient wcSimilarArtists = new WebClient();
                    wcSimilarArtists.DownloadStringCompleted += new DownloadStringCompletedEventHandler(Band_SimilarArtists);
                    wcSimilarArtists.DownloadStringAsync(new Uri("http://www.metal-archives.com/band/ajax-recommendations/id/" + link.Substring(link.LastIndexOf("/") + 1)));

                    //Related Links
                    WebClient wcRelatedLinks = new WebClient();
                    wcRelatedLinks.DownloadStringCompleted += new DownloadStringCompletedEventHandler(Band_RelatedLinks);
                    wcRelatedLinks.DownloadStringAsync(new Uri("http://www.metal-archives.com/link/ajax-list/type/band/id/" + link.Substring(link.LastIndexOf("/") + 1)));
                }
            }
        }

        public void Band_About(HtmlAgilityPack.HtmlDocument bandHTML)
        {
            string leftBandInfo = bandHTML.DocumentNode.Descendants("dl").First(x => x.InnerText.Contains("Country")).InnerHtml;
            string rightBandInfo = bandHTML.DocumentNode.Descendants("dl").First(x => x.InnerText.Contains("Genre")).InnerHtml;

            //Top info
            string bandName;
            //Left info
            string country, location, status, year;
            //Right info
            string genre, lyrics, label;

            //split up top band info
            bandName = bandHTML.DocumentNode.Descendants("h1").First().InnerText;


            //Split up leftBandInfo
            leftBandInfo = leftBandInfo.Substring(leftBandInfo.IndexOf("<dd>") + 4);
            leftBandInfo = leftBandInfo.Substring(leftBandInfo.IndexOf(">") + 1);

            country = leftBandInfo.Substring(0, leftBandInfo.IndexOf("<"));

            leftBandInfo = leftBandInfo.Substring(leftBandInfo.IndexOf("<dd>") + 4);

            location = leftBandInfo.Substring(0, leftBandInfo.IndexOf("<"));

            leftBandInfo = leftBandInfo.Substring(leftBandInfo.IndexOf("<dd") + 3);
            leftBandInfo = leftBandInfo.Substring(leftBandInfo.IndexOf(">") + 1);

            status = leftBandInfo.Substring(0, leftBandInfo.IndexOf("<"));

            leftBandInfo = leftBandInfo.Substring(leftBandInfo.IndexOf("<dd>") + 4);

            year = leftBandInfo.Substring(0, leftBandInfo.IndexOf("<"));


            //Split up rightBandInfo
            rightBandInfo = rightBandInfo.Substring(rightBandInfo.IndexOf("<dd>") + 4);

            genre = rightBandInfo.Substring(0, rightBandInfo.IndexOf("<"));

            rightBandInfo = rightBandInfo.Substring(rightBandInfo.IndexOf("<dd>") + 4);

            lyrics = rightBandInfo.Substring(0, rightBandInfo.IndexOf("<"));

            rightBandInfo = rightBandInfo.Substring(rightBandInfo.IndexOf("<dd>") + 4);
            if (rightBandInfo.Contains("href"))
            {
                rightBandInfo = rightBandInfo.Substring(rightBandInfo.IndexOf(">") + 1);
            }

            label = rightBandInfo.Substring(0, rightBandInfo.IndexOf("<"));


            //Fill in TextBlock
            List<Links> linksInCat = new List<Links>();
            linksInCat.Add(new Links("band name:", "", color, bandName));
            linksInCat.Add(new Links("country of origin:", "", color, country));
            linksInCat.Add(new Links("location:", "", color, location));
            linksInCat.Add(new Links("genre:", "", color, genre));
            linksInCat.Add(new Links("lyrical themes:", "", color, lyrics));
            linksInCat.Add(new Links("status:", "", color, status));
            linksInCat.Add(new Links("current label:", "", color, label));
            linksInCat.Add(new Links("year of creation:", "", color, year));
            this.lsbAbout.ItemsSource = linksInCat;
        }

        public void Band_Discog()
        {
            List<LinkCats> ddDiscogDataSource = new List<LinkCats>();
            ddDiscogDataSource.Add(new LinkCats("complete discography", "", new List<Links>()));
            ddDiscogDataSource.Add(new LinkCats("main", "", new List<Links>()));
            ddDiscogDataSource.Add(new LinkCats("lives", "", new List<Links>()));
            ddDiscogDataSource.Add(new LinkCats("demos", "", new List<Links>()));
            ddDiscogDataSource.Add(new LinkCats("misc", "", new List<Links>()));
            this.ddDiscog.ItemsSource = ddDiscogDataSource;

            //All
            WebClient wcDiscogAll = new WebClient();
            Uri discogAllURI = new Uri("http://www.metal-archives.com/band/discography/id/" + link.Substring(link.LastIndexOf("/") + 1) + "/tab/all");
            wcDiscogAll.DownloadStringCompleted += new DownloadStringCompletedEventHandler(Band_Discog);
            wcDiscogAll.DownloadStringAsync(discogAllURI, discogAllURI);
            //Main
            WebClient wcDiscogMain = new WebClient();
            Uri discogMainURI = new Uri("http://www.metal-archives.com/band/discography/id/" + link.Substring(link.LastIndexOf("/") + 1) + "/tab/main");
            wcDiscogMain.DownloadStringCompleted += new DownloadStringCompletedEventHandler(Band_Discog);
            wcDiscogMain.DownloadStringAsync(discogMainURI, discogMainURI);
            //Lives
            WebClient wcDiscogLives = new WebClient();
            Uri discogLivesURI = new Uri("http://www.metal-archives.com/band/discography/id/" + link.Substring(link.LastIndexOf("/") + 1) + "/tab/lives");
            wcDiscogLives.DownloadStringCompleted += new DownloadStringCompletedEventHandler(Band_Discog);
            wcDiscogLives.DownloadStringAsync(discogLivesURI, discogLivesURI);
            //Demos
            WebClient wcDiscogDemos = new WebClient();
            Uri discogDemosURI = new Uri("http://www.metal-archives.com/band/discography/id/" + link.Substring(link.LastIndexOf("/") + 1) + "/tab/demos");
            wcDiscogDemos.DownloadStringCompleted += new DownloadStringCompletedEventHandler(Band_Discog);
            wcDiscogDemos.DownloadStringAsync(discogDemosURI, discogDemosURI);
            //Misc
            WebClient wcDiscogMisc = new WebClient();
            Uri discogMiscURI = new Uri("http://www.metal-archives.com/band/discography/id/" + link.Substring(link.LastIndexOf("/") + 1) + "/tab/misc");
            wcDiscogMisc.DownloadStringCompleted += new DownloadStringCompletedEventHandler(Band_Discog);
            wcDiscogMisc.DownloadStringAsync(discogMiscURI, discogMiscURI);
        }

        public void Band_Discog(object sender, DownloadStringCompletedEventArgs e)
        {
            if (cm.isOnlineE(e))
            {
                string discogType = ((Uri)e.UserState).AbsoluteUri.Substring(
                                        ((Uri)e.UserState).AbsoluteUri.LastIndexOf("/") + 1
                                    );
                int discogTypeIndex = 0;
                switch (discogType)
                {
                    case "all":
                        discogTypeIndex = 0;
                        break;
                    case "main":
                        discogTypeIndex = 1;
                        break;
                    case "lives":
                        discogTypeIndex = 2;
                        break;
                    case "demos":
                        discogTypeIndex = 3;
                        break;
                    case "misc":
                        discogTypeIndex = 4;
                        break;
                }

                List<LinkCats> ddDiscogDataSource = (List<LinkCats>)this.ddDiscog.ItemsSource;
                HtmlAgilityPack.HtmlDocument bandHTML = new HtmlAgilityPack.HtmlDocument();
                bandHTML.LoadHtml("<HTML>" + e.Result + "</HTML>");
                if (!bandHTML.DocumentNode.Descendants("td").First().InnerHtml.Contains("Nothing entered yet."))
                {
                    string ddDiscogHTML = bandHTML.DocumentNode.Descendants("tbody").First().InnerHtml;

                    while (ddDiscogHTML.Contains("<a"))
                    {
                        ddDiscogHTML = ddDiscogHTML.Substring(ddDiscogHTML.IndexOf("href") + 6);

                        string linkPath = ddDiscogHTML.Substring(0, ddDiscogHTML.IndexOf("\""));

                        ddDiscogHTML = ddDiscogHTML.Substring(ddDiscogHTML.IndexOf(">") + 1);

                        string linkName = ddDiscogHTML.Substring(0, ddDiscogHTML.IndexOf("</a"));

                        ddDiscogHTML = ddDiscogHTML.Substring(ddDiscogHTML.IndexOf("<td"));
                        ddDiscogHTML = ddDiscogHTML.Substring(ddDiscogHTML.IndexOf(">") + 1);

                        string linkDesc = ddDiscogHTML.Substring(0, ddDiscogHTML.IndexOf("</td"));

                        ddDiscogHTML = ddDiscogHTML.Substring(ddDiscogHTML.IndexOf("<td"));
                        ddDiscogHTML = ddDiscogHTML.Substring(ddDiscogHTML.IndexOf(">") + 1);

                        linkDesc += " (" + ddDiscogHTML.Substring(0, ddDiscogHTML.IndexOf("</td")) + ")";

                        ddDiscogHTML = ddDiscogHTML.Substring(ddDiscogHTML.IndexOf("<td"));
                        ddDiscogHTML = ddDiscogHTML.Substring(ddDiscogHTML.IndexOf(">") + 1);

                        if (!ddDiscogHTML.Substring(0, ddDiscogHTML.IndexOf("</td")).Contains("nbsp"))
                        {
                            ddDiscogHTML = ddDiscogHTML.Substring(ddDiscogHTML.IndexOf("<a"));
                            ddDiscogHTML = ddDiscogHTML.Substring(ddDiscogHTML.IndexOf(">") + 1);

                            linkDesc += "\nreviews: " + ddDiscogHTML.Substring(0, ddDiscogHTML.IndexOf("</a"));
                        }

                        ddDiscogDataSource[discogTypeIndex].linksInCat.Add(new Links(linkName, linkPath, color, linkDesc));
                    }
                }
                else
                {
                    ddDiscogDataSource[discogTypeIndex].linksInCat.Add(new Links("No releases available", "", color));
                }

                if (discogTypeIndex == 0)
                {
                    lsbDiscog.ItemsSource = ddDiscogDataSource[0].linksInCat;
                }
            }
        }

        private void ddDiscog_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if ((sender as ListPicker).SelectedIndex >= 0)
            {
                if (((sender as ListPicker).SelectedIndex > 0) || 
                    (((sender as ListPicker).SelectedIndex == 0) && (((LinkCats)(sender as ListPicker).SelectedItem).linksInCat.Count > 0)))
                {
                    lsbDiscog.ItemsSource = ((sender as ListPicker).SelectedItem as LinkCats).linksInCat;
                }
            }
        }

        private void lsbDiscog_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if ((sender as ListBox).SelectedIndex != -1)
            {
                Links selected = (sender as ListBox).SelectedItem as Links;
                if (selected.linkPath.Length > 0)
                {
                    NavigationService.Navigate(new Uri(
                            "/Album.xaml?name=" + selected.linkName + "&link=" + selected.linkPath
                            , UriKind.Relative));
                }
            }
        }

        public void Band_LogoPhoto(HtmlAgilityPack.HtmlDocument bandHTML)
        {
            string logoURL = "", photoURL = "";
            try
            {
                string logo = bandHTML.DocumentNode.Descendants("a").First(x => x.Id == "logo").InnerHtml;
                logoURL = logo.Substring(
                    logo.IndexOf("\"") + 1,
                    logo.Substring(logo.IndexOf("\"") + 1).IndexOf("\"")
                );
            }
            catch { }

            try
            {
                string photo = bandHTML.DocumentNode.Descendants("a").First(x => x.Id == "photo").InnerHtml;
                photoURL = photo.Substring(
                    photo.IndexOf("\"") + 1,
                    photo.Substring(photo.IndexOf("\"") + 1).IndexOf("\"")
                );
            }
            catch { }

            string imageHTML = "<HTML><HEAD><META NAME=\"viewport\" CONTENT=\"WIDTH=420\" ID=\"viewport\" /></HEAD>" +
                "<BODY BGCOLOR=\"#000000\">";
            if (logoURL.Length > 0) { imageHTML += "<IMG SRC=\"" + logoURL + "\"><br />"; }
            if (photoURL.Length > 0) { imageHTML += "<IMG SRC=\"" + photoURL + "\">"; }
            imageHTML += "</body></html>";

            wbLogoPhoto.NavigateToString(imageHTML);
        }

        public void Band_Members(HtmlAgilityPack.HtmlDocument bandHTML)
        {
            List<LinkCats> ddMembersDataSource = new List<LinkCats>();
            string ddMembersHTML = bandHTML.DocumentNode.Descendants("div").Last(x => x.Id == "band_members").InnerHtml;

            while (ddMembersHTML.Contains("<li>"))
            {
                ddMembersHTML = ddMembersHTML.Substring(ddMembersHTML.IndexOf("<li>") + 4);
                ddMembersHTML = ddMembersHTML.Substring(ddMembersHTML.IndexOf("href") + 7);

                string linkCatAnchor = ddMembersHTML.Substring(0, ddMembersHTML.IndexOf("\""));

                ddMembersHTML = ddMembersHTML.Substring(ddMembersHTML.IndexOf(">") + 1);

                string linkCatName = ddMembersHTML.Substring(0, ddMembersHTML.IndexOf("</")).ToLower();

                List<Links> linksInCat = new List<Links>();
                string linksInCatHTML = bandHTML.DocumentNode.Descendants("div").First(x => x.Id == linkCatAnchor).InnerHtml;

                while (linksInCatHTML.Contains("<tr"))
                {
                    linksInCatHTML = linksInCatHTML.Substring(linksInCatHTML.IndexOf("<tr") + 3);
                    linksInCatHTML = linksInCatHTML.Substring(linksInCatHTML.IndexOf("href") + 6);

                    string linkPath = linksInCatHTML.Substring(0, linksInCatHTML.IndexOf("\""));

                    linksInCatHTML = linksInCatHTML.Substring(linksInCatHTML.IndexOf(">") + 1);

                    string linkName = linksInCatHTML.Substring(0, linksInCatHTML.IndexOf("</a"));

                    linksInCatHTML = linksInCatHTML.Substring(linksInCatHTML.IndexOf("<td") + 4);

                    string linkDesc = linksInCatHTML.Substring(0, linksInCatHTML.IndexOf("</td")).Trim();
                    linkDesc = linkDesc.Replace("\t", " ");
                    while (linkDesc.Contains("  "))
                    {
                        linkDesc = linkDesc.Replace("  ", " ");
                    }

                    linksInCatHTML = linksInCatHTML.Substring(linksInCatHTML.IndexOf("<tr") + 3);

                    linksInCat.Add(new Links(linkName, linkPath, color, linkDesc));
                }

                if (!linkCatName.ToLower().Contains("complete"))
                {
                    ddMembersDataSource.Add(new LinkCats(linkCatName, linkCatAnchor, linksInCat));
                }
            }

            this.ddMembers.ItemsSource = ddMembersDataSource;
            this.lsbMembers.ItemsSource = ddMembersDataSource[0].linksInCat;
        }

        private void ddMembers_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if ((sender as ListPicker).SelectedIndex >= 0)
            {
                lsbMembers.ItemsSource = ((sender as ListPicker).SelectedItem as LinkCats).linksInCat;
            }
        }

        private void lsbMembers_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if ((sender as ListBox).SelectedIndex != -1)
            {
                Links selected = (sender as ListBox).SelectedItem as Links;
                NavigationService.Navigate(new Uri(
                    "/Artist.xaml?name=" + selected.linkName + "&link=" + selected.linkPath
                    , UriKind.Relative));
            }
        }

        public void Band_SimilarArtists(object sender, DownloadStringCompletedEventArgs e)
        {
            if (cm.isOnlineE(e))
            {
                HtmlAgilityPack.HtmlDocument bandHTML = new HtmlAgilityPack.HtmlDocument();
                bandHTML.LoadHtml("<HTML>" + e.Result + "</HTML>");

                string ddSimilarArtistsHTML = bandHTML.DocumentNode.Descendants("tbody").First().InnerHtml;

                int numberOfResults = 0;
                string SACounter = ddSimilarArtistsHTML;

                //How many similar artists?
                if (!SACounter.Contains("No similar artist has been recommended yet."))
                {
                    while (SACounter.Contains("<tr"))
                    {
                        numberOfResults++;
                        SACounter = SACounter.Substring(SACounter.IndexOf("<tr") + 3);
                    }
                }

                //Display list of similar artists
                List<Links> linksInCat = new List<Links>();
                while (numberOfResults > 0)
                {
                    numberOfResults--;

                    ddSimilarArtistsHTML = ddSimilarArtistsHTML.Substring(ddSimilarArtistsHTML.IndexOf("<tr") + 3);
                    ddSimilarArtistsHTML = ddSimilarArtistsHTML.Substring(ddSimilarArtistsHTML.IndexOf("<a") + 9);

                    string linkPath = ddSimilarArtistsHTML.Substring(0, ddSimilarArtistsHTML.IndexOf("\""));

                    ddSimilarArtistsHTML = ddSimilarArtistsHTML.Substring(ddSimilarArtistsHTML.IndexOf(">") + 1);

                    string linkName = ddSimilarArtistsHTML.Substring(0, ddSimilarArtistsHTML.IndexOf("</a"));

                    ddSimilarArtistsHTML = ddSimilarArtistsHTML.Substring(ddSimilarArtistsHTML.IndexOf("<td>") + 4);

                    string linkDesc = "country: " + ddSimilarArtistsHTML.Substring(0, ddSimilarArtistsHTML.IndexOf("</td"));

                    ddSimilarArtistsHTML = ddSimilarArtistsHTML.Substring(ddSimilarArtistsHTML.IndexOf("<td>") + 4);

                    linkDesc += "\ngenre: " + ddSimilarArtistsHTML.Substring(0, ddSimilarArtistsHTML.IndexOf("</td"));

                    ddSimilarArtistsHTML = ddSimilarArtistsHTML.Substring(ddSimilarArtistsHTML.IndexOf("<span"));
                    ddSimilarArtistsHTML = ddSimilarArtistsHTML.Substring(ddSimilarArtistsHTML.IndexOf(">") + 1);

                    linkDesc += "\nscore: " + ddSimilarArtistsHTML.Substring(0, ddSimilarArtistsHTML.IndexOf("</span"));

                    linksInCat.Add(new Links(linkName, linkPath, color, linkDesc));
                }
                this.lsbSimilarArtists.ItemsSource = linksInCat;
            }
        }

        private void lsbSimilarArtists_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if ((sender as ListBox).SelectedIndex != -1)
            {
                Links selected = (sender as ListBox).SelectedItem as Links;
                NavigationService.Navigate(new Uri(
                    "/Band.xaml?name=" + selected.linkName + "&link=" + selected.linkPath
                    , UriKind.Relative));
            }
        }

        public void Band_RelatedLinks(object sender, DownloadStringCompletedEventArgs e)
        {
            if (cm.isOnlineE(e))
            {
                HtmlAgilityPack.HtmlDocument bandHTML = new HtmlAgilityPack.HtmlDocument();
                bandHTML.LoadHtml("<HTML>" + e.Result + "</HTML>");

                string ddLinksHTML = bandHTML.DocumentNode.Descendants("ul").First().InnerHtml;

                List<LinkCats> ddLinksDataSource = new List<LinkCats>();

                while (ddLinksHTML.Contains("href"))
                {
                    ddLinksHTML = ddLinksHTML.Substring(ddLinksHTML.IndexOf("href") + 7);

                    string linkCatAnchor = ddLinksHTML.Substring(0, ddLinksHTML.IndexOf("\""));

                    ddLinksHTML = ddLinksHTML.Substring(ddLinksHTML.IndexOf(">") + 1);

                    string linkCatName = ddLinksHTML.Substring(0, ddLinksHTML.IndexOf("</a")).ToLower();

                    List<Links> linksInCat = new List<Links>();
                    string linksInCatHTML = bandHTML.DocumentNode.Descendants("div").First(x => x.Id == linkCatAnchor).InnerHtml;

                    while (linksInCatHTML.Contains("<a"))
                    {
                        linksInCatHTML = linksInCatHTML.Substring(linksInCatHTML.IndexOf("href") + 6);

                        string linkPath = linksInCatHTML.Substring(0, linksInCatHTML.IndexOf("\""));

                        linksInCatHTML = linksInCatHTML.Substring(linksInCatHTML.IndexOf(">") + 1);

                        string linkName = linksInCatHTML.Substring(0, linksInCatHTML.IndexOf("</a"));

                        linksInCat.Add(new Links(linkName, linkPath, color));
                    }

                    ddLinksDataSource.Add(new LinkCats(linkCatName, linkCatAnchor, linksInCat));
                }

                this.ddLinks.ItemsSource = ddLinksDataSource;
                this.lsbLinks.ItemsSource = ddLinksDataSource[0].linksInCat;
            }
        }

        private void ddLinks_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if ((sender as ListPicker).SelectedIndex >= 0)
            {
                lsbLinks.ItemsSource = ((sender as ListPicker).SelectedItem as LinkCats).linksInCat;
            }
        }

        private void lsbLinks_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if ((sender as ListBox).SelectedIndex != -1)
            {
                Links selected = (sender as ListBox).SelectedItem as Links;
                WebBrowserTask browser = new WebBrowserTask();
                browser.Uri = new Uri(selected.linkPath, UriKind.Absolute);
                browser.Show();
            }
        }
    }
}